<template>
  <div>

    <el-drawer
      :wrapperClosable="false"
      :title="title"
      :visible.sync="open"
      direction="rtl"
      :style="{ right: `${drawerSkewing}px`,  'transition': '.2s' }"
    >
      <el-container>
        <el-main>
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-position="top"
            label-width="80px"
          >

            <!-- 功能标识 -->
            <el-form-item label="功能标识" prop="id">
              <el-input :disabled="idDisabled" v-model="form.id" placeholder="请输入功能标识" />
            </el-form-item>

            <!-- 功能名称 -->
            <el-form-item label="功能名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入功能名称" />
            </el-form-item>

            <!-- 是否异步 -->
            <el-form-item label="是否异步" prop="async">
              <el-radio-group v-model="form.async">
                <el-radio
                  v-for="dict in dict.type.iot_is_async"
                  :key="dict.value" :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 输入参数 -->
            <el-form-item label="输入参数">
              <el-row v-show="form.inputs.length > 0">
                <el-card body-style="padding: 3px" shadow="never">
                  <el-row v-for="(item, index) in form.inputs">
                    <el-col :span="17" :offset="1">参数名称：{{ item.name }}</el-col>
                    <el-col :span="6">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        v-hasPermi="['iot:product:edit']"
                        @click="handleChildUpdate(item)"
                      >编辑</el-button>
                      <el-divider direction="vertical"></el-divider>
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-delete"
                        v-hasPermi="['iot:product:remove']"
                        @click="handleChildDelete(index)"
                      >删除</el-button>
                    </el-col>
                  </el-row>
                </el-card>
              </el-row>
              <el-row>
                <el-col :span="23" :offset="1">
                  <el-button icon="el-icon-plus" type="text" @click="handleChildAdd">添加参数</el-button>
                </el-col>
              </el-row>
            </el-form-item>

            <!-- 输出参数表单 -->
            <value-type-add-edit
              :form-data="this.form.output"
              ref="valueTypeAddEdit"
              @child-visible="handleChildVisible"
              :visible="open"
              type-label="输出参数"
            />

            <!-- 描述 -->
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
        </el-main>
        <el-footer>
          <div class="bottom-bar" style="text-align:right">
            <el-button @click="cancel">关 闭</el-button>
            <el-popover
              v-if="submitType === 'save&deploy'"
              popper-class="popper"
              style="margin-left: 10px;"
              placement="top"
              width="100px"
              v-model="popoverVisible"
              trigger="hover"
            >
              <div style="text-align: left;">
                <div>
                  <el-button size="small" @click="submitForm">仅保存</el-button>
                </div>
                <div style="margin-top: 10px">
                  <el-button size="small" @click="submitDeployForm">保存并生效</el-button>
                </div>
              </div>
              <el-button icon="el-icon-arrow-down" type="primary" slot="reference">保 存</el-button>
            </el-popover>
            <el-button v-if="submitType === 'save'" type="primary" @click="submitForm">保 存</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-drawer>

    <!-- 子表单添加或修改对话框 -->
    <properties-child-add-edit
      @visible="handleChildVisible"
      @data="handleChildData"
      ref="propertiesChildAddEdit"
    />

  </div>

</template>

<script>
import ValueTypeAddEdit from '@/views/iot/product/physical-model/valueTypeAddEdit'
import PropertiesChildAddEdit from '@/views/iot/product/physical-model/propertiesChildAddEdit'
import utils from '@/utils/iot/metadata'

export default {
  name: 'FunctionsAddEdit',
  components: {
    PropertiesChildAddEdit,
    ValueTypeAddEdit
  },
  // 字典
  dicts: [
    // 是否异步
    'iot_is_async'
  ],
  props: {
    submitType: {
      type: String,
      default: 'save&deploy'
    }
  },
  data() {
    return {
      // 对话框标题
      title: undefined,
      // 对话框显示状态（默认隐藏）
      open: false,
      // 防止抽屉关闭时Popover 弹出框还未关闭
      popoverVisible: false,
      // 抽屉偏移大小
      drawerSkewing: 0,
      // 表单参数
      form: {
        // 输入参数
        inputs: [],
        // 输出参数
        output: {
          // 拓展定义
          expands: {},
          // 枚举数据
          elements: [{}],
          // 元素类型
          elementType: {
            // 拓展定义
            expands: {},
            // 枚举数据
            elements: [{}],
            // JSON 对象
            properties: []
          },
          // JSON 对象
          properties: []
        }
      },
      // 标识默认非禁用的
      idDisabled: false,
      // 表单校验
      rules: {
        id: [
          { required: true, message: '功能标识不能为空', trigger: 'change' }
        ],
        name: [
          { required: true, message: '功能名称不能为空', trigger: 'change' }
        ],
        async: [
          { required: true, message: '请选择是或者否', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        name: null,
        // 输入参数
        inputs: [],
        // 输出参数
        output: {
          // 扩展定义
          expands: {},
          // 枚举数据
          elements: [{}],
          // 元素类型
          elementType: {
            // 拓展定义
            expands: {},
            // 枚举数据
            elements: [{}],
            // JSON 对象
            properties: []
          },
          // JSON 对象
          properties: []
        },
        description: null
      }
      this.resetForm('form')
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 标识还原成可输入状态
      this.idDisabled = false
      this.open = true
      this.title = '添加功能'
    },
    /** 子表单添加按钮操作*/
    handleChildAdd() {
      this.$refs.propertiesChildAddEdit.handleAdd()
    },
    /** 子表单更新按钮操作*/
    handleChildUpdate(data) {
      data = JSON.parse(JSON.stringify(data))
      this.$refs.propertiesChildAddEdit.handleUpdate(data)
    },
    /** 子表单删除按钮操作*/
    handleChildDelete(index) {
      this.form.inputs.splice(index, 1)
    },
    /** 修改按钮操作 */
    handleUpdate(data) {
      this.reset()
      // 不允许更新标识
      this.idDisabled = true
      this.form = data
      this.open = true
      this.title = '编辑功能'
    },
    /** 提交按钮 */
    async submitForm(publishState) {

      let pass = true

      await this.$refs.valueTypeAddEdit.handleSubmit().then(valid => {
        if (!valid) {
          pass = valid
        }
      })
      await this.$refs['form'].validate(valid => {
        if (!valid) {
          pass = valid
        }
      })

      if (pass) {
        this.$emit('submit', this.form, () => {
          this.$modal.msgSuccess('保存成功')
          // 关闭抽屉
          this.open = false
          this.popoverVisible = false
        }, publishState)
      }
    },
    /** 提交并部署 */
    submitDeployForm() {
      this.submitForm(1)
    },

    /**
     * 根据子页面隐藏与显示偏移当前页面，子页面显示当前页面左偏移200px，关闭还原
     * @param state
     */
    handleChildVisible(state) {
      state ? this.drawerSkewing = 200 : this.drawerSkewing = 0
    },
    /**
     * 接收子页面的表单数据
     * @param data
     */
    handleChildData(data) {
      data = JSON.parse(JSON.stringify(data))
      utils.arraySetValue(this, this.form.inputs, data)
    }

  }
}
</script>

<style lang="scss">
.popper {
  min-width: 100px;
}
</style>
